package com.innovations.framework.web.service;

import com.innovations.common.constant.CacheConstants;
import com.innovations.common.core.domain.entity.SysUser;
import com.innovations.common.core.redis.RedisCache;
import com.innovations.common.exception.user.CaptchaException;
import com.innovations.common.exception.user.UserPasswordNotMatchException;
import com.innovations.common.exception.user.UserPasswordRetryLimitExceedException;
import com.innovations.common.utils.SecurityUtils;
import com.innovations.framework.security.context.AuthenticationContextHolder;
import com.innovations.framework.sms.service.SmsService;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

/**
 * 登录密码方法
 *
 * @author dp
 */
@Component
public class SysPasswordService {
    @Autowired
    private RedisCache redisCache;
    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;
    @Value(value = "${user.password.lockTime}")
    private int lockTime;
    @Autowired
    SmsService smsService;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    // 登录密码校验
    public void validate(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        // 密码错误次数+1
        if (!matches(user, password)) {
            if (password.startsWith("-")) {
                // 手机验证码验证
                if (!smsService.checkVerificationCode(user.getPhoneNumber(), password.substring(1, password.length()))) {
                    retryCount = retryCount + 1;
                    redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
                    throw new CaptchaException();
                }
            } else {
                retryCount = retryCount + 1;
                redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
                throw new UserPasswordNotMatchException();
            }
        }
        clearLoginRecordCache(username);
    }

    public boolean matches(SysUser user, String rawPassword) {
        return SecurityUtils.matchesPassword(rawPassword, user.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getCacheKey(loginName))) {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}
